package com.demo.collector.util.result;

/**
 * @author 沈伟峰
 */
public class JsonResult implements Result {

    public static final JsonResult SUCCESS = new JsonResult(200, "success", null);
    public static final JsonResult FAIL = new JsonResult(400, "fail", null);

    private Integer status;
    private String message;
    private Object data;

    private JsonResult() {
    }

    private JsonResult(Integer status, String message, Object data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    public Integer getStatus() {
        return status;
    }

    public String getMessage() {
        return message;
    }

    public Object getData() {
        return data;
    }

    @Override
    public int status() {
        return status == null ? 0 : status;
    }

    @Override
    public String message() {
        return message;
    }

    @Override
    public Object data() {
        return data;
    }

    public static class Builder {

        private final JsonResult result = new JsonResult();

        public static Builder builder() {
            return new Builder();
        }

        public static JsonResult success(String message, Object data) {
            return new JsonResult(200, message, data);
        }

        public static JsonResult fail(int code, String message) {
            return new JsonResult(code, message, null);
        }

        public Builder status(int status) {
            result.status = status;
            return this;
        }

        public Builder message(String message) {
            result.message = message;
            return this;
        }

        public Builder data(Object data) {
            result.data = data;
            return this;
        }

        public JsonResult build() {
            if (result.status == null) {
                result.status = 200;
            }
            if (result.message == null) {
                if (result.status.equals(SUCCESS.status)) {
                    result.message = SUCCESS.message;
                } else if (result.status.equals(FAIL.status)) {
                    result.message = FAIL.message;
                } else {
                    result.message = "";
                }
            }
            return result;
        }
    }
}
